<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>
        <a href="/">商品管理</a>
      </el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="labelTop">
      <div>
        <el-button type="info" class="wid" disabled>
          <i class="el-icon-info"></i>
          添加商品信息
        </el-button>
      </div>

      <!--步骤条-->
      <el-steps :active="active-'0'" finish-status="success" class="labelTop">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!--标签页-->
      <el-form
        label-width="100px"
        :model="addateForm"
        ref="addateref"
        :rules="Addrules"
        label-position="top"
        class="labelTop"
      >
        <!--选项卡-->
        <el-tabs
          :tab-position="'left'"
          v-model="active"
          @tab-click="triggle"
          :before-leave="tirgger"
        >
          <!--基本信息区-->
          <el-tab-pane name="0" label="基本信息">
            <el-form-item label="商品名称 :" prop="goods_name">
              <el-input v-model="addateForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格 :" prop="goods_price">
              <el-input v-model.number="addateForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量 :" prop="goods_weight">
              <el-input v-model.number="addateForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量 :" prop="goods_number">
              <el-input v-model.number="addateForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类 :" prop="goods_cat">
              <!--级联选择器-->
              <el-cascader
                v-model="addateForm.goods_cat"
                :options="options"
                :props="prop"
                @change="handleChange"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <!--商品参数区动-->
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name+' :'" v-for="item in shopData" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox :label="val" v-for="(val,i) in item.attr_vals" :key="i" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <!--商品属性区静-->
          <el-tab-pane label="商品属性" name="2">
            <el-form-item v-for="(item,int) in shopKey" :key="int" :label="item.attr_name">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <!--商品图片区-->
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :action="views+'upload'"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              list-type="picture"
              :headers="header"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <!--角色区-->
          <el-tab-pane label="商品内容" name="4">
            <quill-editor ref="myQuillEditor" v-model="addateForm.goods_introduce"></quill-editor>
            <el-button type="primary" class="labelTop" @click="sublit()">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!--图片的对话框-->
    <el-dialog title="图片提示" :visible.sync="ImgVisible" width="50%">
      <img :src="imgscr" alt="图片提示" class="imt" />
    </el-dialog>
  </div>
</template>

<script>
export default {
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.getCasc(); //得到级联选择器的内容
  },
  data() {
    return {
      //步骤条进度
      active: 0,
      //基本信息表单存储值
      addateForm: {
        goods_name: "",
        goods_price: "",
        goods_weight: "",
        goods_number: "",
        goods_cat: [], //级联选择器最终存储值
        pics: [], //上传图片的存储位置
        goods_introduce: "", //商品内容
        attrs:[],   //商品的动静态参数
      },
      //基本信息的级联选择器数据
      options: [],
      //级联选择器规则
      prop: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children"
      },
      //验证规则
      Addrules: {
        goods_name: [
          { required: true, message: "请输入文本值", tirgger: "blur" }
        ],
        goods_price: [
          {
            type: "number",
            required: true,
            message: "请输入数值",
            tirgger: "blur"
          }
        ],
        goods_weight: [
          {
            type: "number",
            required: true,
            message: "请输入数值",
            tirgger: "blur"
          }
        ],
        goods_number: [
          {
            type: "number",
            required: true,
            message: "请输入数值",
            tirgger: "blur"
          }
        ],
        goods_cat: [
          {
            required: true,
            type: "array",
            message: "请选择级商品分类",
            tirgger: "blur"
          }
        ]
      },
      //商品参数
      shopData: [],
      //商品属性参数
      shopKey: [],
      //上传图片的根路径
      views: "http://127.0.0.1:8888/api/private/v1/",
      //文件上传的响应头(要设置)
      header: {
        Authorization: window.sessionStorage.getItem("token")
      },
      //图片框
      ImgVisible: false,
      //图片预览地址
      imgscr: ""
    };
  },
  methods: {
    //所有商品分类的数据
    async getCasc() {
      let { data: res } = await this.$http.get("categories");
      if (res.meta.status != 200) {
        return this.$message.error("失败");
      }
      this.options = res.data;
      console.log(res.data);
    },
    //级联选择器的发生变化时
    handleChange() {
      if (!this.addateForm.goods_cat.length >= 3) {
        this.$message.error("请选择正确的商品分类");
        return false;
      }
    },
    //当用户在没选中商品分类时，不给予访问其他项
    tirgger(activeName, oldActiveName) {
      if (activeName > 0 && !this.cateId) {
        //应该是判断当时第一层的所有数据进行预校验
        this.$message("请填写商品分类");
        return false;
      }
    },
    //当Tbs标签页发生切换时
    async triggle() {
      //获得动态商品参数
      if (this.active == "1") {
        //判断步骤一的用户是否有输入所有的文本值，(尚未判断)
        //如果有，发送ajax数据请求成功失败
        //成功，渲染数据，将用户的填充成绑定在/1,2之间
        let { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: {
              sel: "many"
            }
          }
        );
        if (res.meta.status != 200) {
          return this.$message.error("获取动态数据失败");
        }
        this.$message.success("成功");
        //将商品参数的渲染变的字符串变成数组
        res.data.forEach(item => {
          if (item.attr_vals == "") {
            item.attr_vals = [];
          } else {
            item.attr_vals = item.attr_vals.split(" ");
          }
        });
        this.shopData = res.data;
        //console.log("商品参数" + this.shopData);
      }
      //获得动态商品属性
      else if (this.active == "2") {
        let { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: {
              sel: "only"
            }
          }
        );
        if (res.meta.status != 200) {
          return this.$message.error("获取商品属性失败");
        }
        this.shopKey = res.data;
        //console.log("商品属性", this.shopKey);
      }
      console.log(this.active);
    },
    //当图片上传成功时，需要得到图片的临时路径
    handleSuccess(success) {
      //console.log(success);
      //创建一个临时的obj对象
      let obj = {};
      //得到临时的数据库图片路径
      obj.pic = success.data.tmp_path;
      //附加
      this.addateForm.pics.push(obj);
      //console.log(this.addateForm.pics);
    },
    //图片预览效果事件
    handlePreview(file) {
      //console.log(file);
      this.imgscr = file.response.data.url;
      //显示当前的图片地址
      //弹出对图片对话框
      this.ImgVisible = true;
    },
    //当图片上传移除时
    handleRemove(file) {
      //得到目前已经上传的文件存储数组参数路径
      let url = file.response.data.tmp_path;
      let index = this.addateForm.pics.findIndex(item => item == url);
      this.addateForm.pics.splice(index, 1);
      console.log(this.addateForm);
    },
    //最终上传
    sublit(){
     //首先先预验证
     this.$refs.addateref.validate(async (item)=>{
       if(!item){
         return this.$message.error('请填写表单必填项');
       }
        //验证通过
       //console.log(this.addateForm);
       //上交对象
      let form = {};
      //深层拷贝函数
      this.copy(form,this.addateForm);
      //将联选择器的id存储值转化为 字符串
      form.goods_cat = form.goods_cat.join(',');
        //得到动态参数
        this.shopData.forEach(item=>{
          let obj = {};
          obj.attr_id = item.attr_id;
          obj.attr_value = item.attr_vals.join(',');
          form.attrs.push(obj);
        });
        //得到静态
         this.shopKey.forEach(item=>{
          let obj = {};
          obj.attr_id = item.attr_id;
          obj.attr_value = item.attr_vals;
          form.attrs.push(obj);
        });
        //去除内容的标签对
        form.goods_introduce = form.goods_introduce.replace(/<.*?>/ig,'');
        console.log(form);
        //提交
        let {data:res} = await this.$http.post('goods',form);
        if(res.meta.status!=201){
          console.log(res.data);
          return this.$message.error('请求失败');
        }
        //如果成功的话
        this.$message.success('添加商品成功');
        //跳转到页面
        this.$router.push('/goods');
     });
    },
    //深层拷贝
    copy(obj,target){
      for(let key in target){
        if(target[key] instanceof Array){
          obj[key] = [];
          this.copy(obj[key],target[key]);
        }else if(target[key] instanceof Object){
          obj[key] = {};
          this.copy(obj[key],target[key]);
        }else{
          obj[key]=target[key]; 
        }
      }
      return obj;
    }
  },
  computed: {
    //级联选择器的静态id值
    cateId() {
      if (!this.addateForm.goods_cat.length >= 3) {
        return null;
      }
      return this.addateForm.goods_cat[2];
    }
  },
  //挂载完毕
  mounted() {
   document.getElementsByClassName("ql-container")[0].style.height= '200px';
  }
};
</script>
<style scoped>
.wid {
  width: 100%;
}
.labelTop {
  margin-top: 15px;
}
.el-checkbox {
  margin-right: 5px;
}
.imt {
  display: block;
  width: 100%;
  height: 100%;
}
/* @import url(); 引入css类 */
</style>